package com.imooc.mall.filter;


import com.imooc.mall.common.ApiRestResponse;
import com.imooc.mall.common.Constant;
import com.imooc.mall.exception.ImoocMallExceptionEnum;
import com.imooc.mall.model.pojo.User;
import com.imooc.mall.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.LogRecord;

/**
 * 管理员是否登录的过滤器
 */
public class AdminFilter implements Filter {
    @Autowired
    private UserService userService;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }
    @Override
    public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {

        HttpServletRequest servletRequest = (HttpServletRequest) request;
        HttpSession session = servletRequest.getSession();
        //判断当前用户是否已经登录
        User currentUser = (User) session.getAttribute(Constant.IMOOC_MALL_USER);
        if (currentUser==null){
            PrintWriter out = new HttpServletResponseWrapper((HttpServletResponse) response).getWriter();
            out.write("\"status\": 10007,\n" +
                    "    \"msg\": \"NEED_LOGION\",\n" +
                    "    \"data\": null");
            out.flush();
            out.close();
            return;
        }
        //判断该用户是否是管理员
        Boolean aBoolean = userService.checkAdminRole(currentUser);
        if (aBoolean){
            //进行放行操作
            chain.doFilter(request,response);

        }else {
            PrintWriter out = new HttpServletResponseWrapper((HttpServletResponse) response).getWriter();
            out.write("\"status\": 10009,\n" +
                    "    \"msg\": \"NEED_ADMIN\",\n" +
                    "    \"data\": null");
        out.flush();
        out.close();
        }
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
